package com.itheima.service.db.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.domain.db.AnalysisByDay;
import com.itheima.mapper.AnalysisByDayMapper;
import com.itheima.mapper.LogMapper;
import com.itheima.service.db.AnalysisByDayService;
import com.itheima.util.ComputeUtil;
import com.itheima.vo.AnalysisSummaryVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class AnalysisByDayServiceImpl implements AnalysisByDayService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    //分析log,生成tb_analysis_by_day
    @Override
    public void analysis() {
        System.out.println("========================开始日志分析=========================");
        String today = DateUtil.offsetDay(new Date(), 0).toDateStr();
        String yesterday = DateUtil.offsetDay(new Date(), -1).toDateStr();

        //0. 准备AnalysisByDay对象
        Integer numRegistered = logMapper.countByTimeAndType(today, "0102").intValue();//新注册用户数
        Integer numActive = logMapper.countByTime(today).intValue();//活跃用户数
        Integer numLogin = logMapper.countByTimeAndType(today, "0101").intValue();//登录次数
        Integer numRetention1d = logMapper.keep(yesterday, today).intValue();//次日留存用户数

        //1. 先查询是否存在今天的统计数据
        QueryWrapper<AnalysisByDay> wrapper = new QueryWrapper<>();
        wrapper.eq("record_date", today);
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(wrapper);

        if (analysisByDay == null) {
            //2. 如果不存在,保存
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(new Date());
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumActive(numActive);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumRetention1d(numRetention1d);

            analysisByDayMapper.insert(analysisByDay);
        } else {
            //3. 如果存在,更新
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumActive(numActive);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumRetention1d(numRetention1d);
            analysisByDayMapper.updateById(analysisByDay);
        }
    }

    @Override
    public AnalysisSummaryVo analysisSummary() {
        //1. 基础数据准备
        //1-1 日期
        String today = DateUtil.offsetDay(new Date(), 0).toDateStr();
        String today_30 = DateUtil.offsetDay(new Date(), -30).toDateStr();
        String today_7 = DateUtil.offsetDay(new Date(), -7).toDateStr();
        String yesterday = DateUtil.offsetDay(new Date(), -1).toDateStr();

        //1-2 查询今日数据
        QueryWrapper<AnalysisByDay> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("record_date", today);
        AnalysisByDay todayData = analysisByDayMapper.selectOne(wrapper1);

        //1-3 查询昨日日数据
        QueryWrapper<AnalysisByDay> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("record_date", yesterday);
        AnalysisByDay yesterdayData = analysisByDayMapper.selectOne(wrapper2);

        //2. 查询9个数据
        //累计用户数(每天注册数加和)
        Long cumulativeUsers = analysisByDayMapper.countRegisterNum();
        //过去30天活跃用户数
        Long activePassMonth = analysisByDayMapper.countActiveNum(today_30, today);
        //过去7天活跃用户
        Long activePassWeek = analysisByDayMapper.countActiveNum(today_7, today);
        //今日新增用户数量
        Long newUsersToday = todayData.getNumRegistered().longValue();
        //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌   BigDecimal : 商业数字格式
        BigDecimal newUsersTodayRate = ComputeUtil.computeRate(todayData.getNumRegistered(), yesterdayData.getNumRegistered());
        //今日登录次数
        Long loginTimesToday = todayData.getNumLogin().longValue();
        //今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        BigDecimal loginTimesTodayRate = ComputeUtil.computeRate(todayData.getNumLogin(),yesterdayData.getNumLogin());
        //今日活跃用户数量
        Long activeUsersToday = todayData.getNumActive().longValue();
        //今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        BigDecimal activeUsersTodayRate = ComputeUtil.computeRate(todayData.getNumActive(),yesterdayData.getNumActive());


        //3. 组装AnalysisSummaryVo对象
        AnalysisSummaryVo analysisSummaryVo = new AnalysisSummaryVo();
        analysisSummaryVo.setCumulativeUsers(cumulativeUsers);
        analysisSummaryVo.setActivePassMonth(activePassMonth);
        analysisSummaryVo.setActivePassWeek(activePassWeek);
        analysisSummaryVo.setNewUsersToday(newUsersToday);
        analysisSummaryVo.setNewUsersTodayRate(newUsersTodayRate);
        analysisSummaryVo.setLoginTimesToday(loginTimesToday);
        analysisSummaryVo.setLoginTimesTodayRate(loginTimesTodayRate);
        analysisSummaryVo.setActiveUsersToday(activeUsersToday);
        analysisSummaryVo.setActiveUsersTodayRate(activeUsersTodayRate);

        return analysisSummaryVo;
    }

    @Override
    public Integer findByTime(String everyDay, String type) {
        if (type.equals("101")){
            return analysisByDayMapper.findNumRegistered(everyDay);
        }else if (type.equals("102")){
            return analysisByDayMapper.findNumActive(everyDay);
        }else if (type.equals("103")){
            return analysisByDayMapper.findNumRetention1d(everyDay);
        }
        return null;
    }
}
